import { ref } from 'vue';
import store from "@/store";

export default function useWebSocket(url) {
    const messagesData = ref([]);

    // 创建WebSocket连接和相关方法
    const socket = new WebSocket(url);

    socket.onopen = () => {
        console.log('WebSocket连接已建立');
    };

    socket.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        store.state.alarmBox = true
        store.state.websocketData = receivedMessage;
        console.log('接收到消息:', store.state.websocketData);
        //接收到后端消息，根据业务逻辑自行处理
    };

    socket.onclose = () => {
        console.log('WebSocket连接已关闭');
    };
    return {
        messagesData,
        sendMessage: (message) => {
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(message);
            }
        },
        closeConnection: () => {
            socket.close();
        }
    };
}
